package cn.tedu.connection;

import cn.tedu.pojo.Student;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Arrays;

@RestController
@RequestMapping("stu")
@CrossOrigin//放行所有的请求，解决跨域问题
public class StuConnection {
    @RequestMapping("add")
    public Student add(Student s) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost:3307/py-school-db?characterEncoding=utf8";
        Connection conn = DriverManager.getConnection(url,"root","123456");

        String sql = "insert into student values(?,?,?,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,s.getName());
        ps.setInt(2,s.getAge());
        ps.setInt(3,s.getSex());
        ps.setInt(4,s.getEdu());
        String hs = Arrays.toString(s.getHobby());
        ps.setString(5,hs.substring(1,hs.length()-1));
        ps.setDate(6,new Date(new java.util.Date().getTime()));
        ps.executeLargeUpdate();
        ps.close();
        conn.close();
        System.out.println("数据入库成功");
        return s;
    }
}
